/*
** hexdump.c for kdump in /home/matt/Desktop/ensuitetrace/kdump
** 
** Made by mathieu1 lornac
** Login   <lornac_a@epitech.net>
** 
** Started on  Wed Jan  5 21:10:37 2011 mathieu1 lornac
** Last update Wed Jan  5 22:19:39 2011 mathieu1 lornac
*/

#include <stdio.h>
#include <sys/ioctl.h>
#include <termcap.h>
#include <stdlib.h>
#include <unistd.h>

int getwidth(void)
{
  struct winsize st;
  if (ioctl(0, TIOCGWINSZ, &st) < 0)
    {
      printf("can't get screen size\n");
      exit(1);
    }
  if (st.ws_col - 12 < 5)
    {
      printf("Screen too small\n");
      exit(1);
    }
  return (st.ws_col - 12) / 5;
}

void my_hexdump(char *p, int size)
{
  int width = getwidth();
  unsigned int addr = 0;
  char ch[255];

  while (size > 0)
    {
      printf("\t0x%04x ", addr);
      int i = -1;
      while (i < width)
	{
	  if (i++ & 1)
	    printf(" ");
	  printf("%02hhx", *p);
	  if (*p < 32 || *p > 126)
	    ch[i] = '.';
	  else
	    ch[i] = *p;
	  ++p;
	}
      ch[i] = 0;
      printf("  |%s|\n", ch);
      size -= width;
      addr += width;
    }
}
